package bjtu.cit.bookshop.controller;

import bjtu.cit.bookshop.common.ErrorCode;
import bjtu.cit.bookshop.common.ShoppingCart;
import bjtu.cit.bookshop.entities.Book;
import bjtu.cit.bookshop.entities.Order;
import bjtu.cit.bookshop.entities.OrderBook;
import bjtu.cit.bookshop.entities.User;
import bjtu.cit.bookshop.service.IBookService;
import bjtu.cit.bookshop.service.IOrderService;
import bjtu.cit.bookshop.service.IUserService;
import org.omg.CORBA.INTERNAL;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jia19 on 2015/10/29.
 */
@Controller
@RequestMapping("/")
public class ShopCartController extends BaseController {

    @Resource
    private IBookService bookService = null;

    @Resource
    private IUserService userService = null;

    @Resource
    private IOrderService orderService = null;

    @RequestMapping("shoppingCart")
    public String shoppingCart(HttpSession session, ModelMap model) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            model.addAttribute("isLogin", false);
        }
        else {
            model.addAttribute("isLogin", true);
            model.addAttribute("loginName", loginName);
            model.addAttribute("current", "cart");
            ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("cart");
            if (shoppingCart == null) {
                shoppingCart = new ShoppingCart();
                session.setAttribute("cart", shoppingCart);
            }
            List<ShoppingCart.CartBook> list = shoppingCart.getBookList();
            for (ShoppingCart.CartBook book : list) {
                Book b = bookService.getBookById(book.getBookId());
                if (b != null) {
                    book.setName(b.getBookname());
                    book.setPrice(b.getPrice());
                }
                else {
                    list.remove(book);
                }
            }
            model.addAttribute("bookList", list);
        }
        return "buycar";
    }

    @RequestMapping("delFromCart.do")
    public String delFromCart(HttpSession session, HttpServletRequest request, ModelMap model) {
        if (checkLogin(session) == null) {
            model.addAttribute("errmsg", "没有该权限！");
            return "error";
        }
        String str_id = request.getParameter("bookid");
        try {
            int id = Integer.parseInt(str_id);
            ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("cart");
            shoppingCart.delBook(id);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("errmsg", "参数错误！");
            return "error";
        }
        return "redirect:/shoppingCart.do";
    }

    @RequestMapping("addToCart.do")
    @ResponseBody
    public ErrorCode addToCart(HttpSession session, HttpServletRequest request) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            return NO_AUTH;
        }
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            cart = new ShoppingCart();
            session.setAttribute("cart", cart);
        }
        String str_id = request.getParameter("id");
        String str_num = request.getParameter("num");
        try {
            int id = Integer.parseInt(str_id);
            int num = Integer.parseInt(str_num);
            cart.addBook(id, num);
        }catch (Exception e) {
            e.printStackTrace();
            return PARA_ERROR;
        }
        return SUCCESS;
    }

    @RequestMapping("changeNumber.do")
    @ResponseBody
    public ErrorCode changeNumber(HttpSession session, HttpServletRequest request) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            return NO_AUTH;
        }

        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
        if (cart == null) {
            return PARA_ERROR;
        }

        String str_id = request.getParameter("id");
        String str_num = request.getParameter("num");
        try {
            int id = Integer.parseInt(str_id);
            int num = Integer.parseInt(str_num);
            cart.changeNum(id,  num);
        } catch (Exception e) {
            e.printStackTrace();
            return PARA_ERROR;
        }
        return SUCCESS;
    }

    @RequestMapping("buy.do")
    public String buy(HttpSession session, HttpServletRequest request, ModelMap model) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            model.addAttribute("isLogin", false);
            model.addAttribute("errmsg", "还未登录！");
            return "error";
        }
        model.addAttribute("isLogin", true);
        model.addAttribute("loginName", loginName);
        model.addAttribute("current", "cart");

        User user = userService.getUserByUserName(loginName);
        model.addAttribute("user", user);

        return "pay";
    }

    @RequestMapping("order.do")
    @ResponseBody
    public ErrorCode order(HttpSession session, HttpServletRequest request) {
        String loginName = checkLogin(session);
        if (loginName == null) {
            return NO_AUTH;
        }
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("cart");
        if (shoppingCart == null) {
            return PARA_ERROR;
        }
        Order order = new Order();
        List<ShoppingCart.CartBook> list = shoppingCart.getBookList();
        try {
            order.setReceiver(request.getParameter("receiver"));
            order.setAddress(request.getParameter("address"));
            order.setPhone(request.getParameter("phone"));
            order.setUserid((Integer) session.getAttribute("userId"));
            order.setPostcode(request.getParameter("postcode"));
            order.setDeliver(request.getParameter("deliver"));
            order.setPayment(request.getParameter("payment"));
            order.setDate(new Date());
            order.setState("等待发货");

            float totalPrice = 0.0f;
            List<OrderBook> orderBooks = new ArrayList<OrderBook>();

            for(ShoppingCart.CartBook b : list) {
                OrderBook orderBook = new OrderBook();
                orderBook.setBookid(b.getBookId());
                orderBook.setNum(b.getNum());
                orderBooks.add(orderBook);
                totalPrice += b.getPrice().floatValue() * b.getNum();
            }

            BigDecimal total = new BigDecimal(totalPrice);
            order.setTotalprice(total);
            orderService.createAOrder(order, orderBooks);
        }
        catch (Exception e) {
            e.printStackTrace();
            return PARA_ERROR;
        }
        session.setAttribute("cart", null);
        return SUCCESS;
    }
}
